package com.libui.webview.jsinterface.handlers

import com.libbase.utils.ThreadUtils
import com.libui.dialog.DialogEx
import com.libui.webview.WebViewEx
import com.libui.webview.jsinterface.WebViewHandlerInterface

class CloseDialogHandler : WebViewHandlerInterface {
    companion object {
        const val id: String = "closeDialog"
    }

    override val id: String
        get() {
            return Companion.id
        }

    override fun handle(webView: WebViewEx?, params: Map<String, Any>?) {
        if (webView == null) {
            return
        }

        if (params == null) {
            return
        }

        val uuid: String = params["uuid"] as? String ?: return

        val dialogId: String? = params["dialogId"] as? String
        if (dialogId == null) {
            runFailCallback(
                webView, uuid,
                1, "closeDialog:fail, no dialogId", null,
                params
            )
            return
        }

        val buttonId: String? = params["buttonId"] as? String
        if (buttonId == null) {
            runFailCallback(
                webView, uuid,
                2, "closeDialog:fail, no buttonId", null,
                params
            )
            return
        }

        ThreadUtils.instance.executeInMainThread{
            DialogEx.closeDialog(dialogId, buttonId)
        }

        runSuccessCallback(
            webView, uuid,
            0, "closeDialog:ok", null,
            params
        )
    }
}